package club.kingyin.easycache.component.handler;

import club.kingyin.easycache.cache.ValueSerializer;
import club.kingyin.easycache.exception.SerializeException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.text.StringEscapeUtils;

import javax.annotation.Nonnull;

@Deprecated
public class StringJsonEasyCacheSerializer implements ValueSerializer<String> {
    @Override
    public String encode(Object data) throws SerializeException {
        return StringEscapeUtils.unescapeJson(JSON.toJSONString(data));
    }

    @Override
    public Object decode(String sources) throws SerializeException {
        try {
            if (!isJSON2(sources)) {
                return sources;
            }
            return JSONObject.parse(sources);
        } catch (Exception e) {
            throw new SerializeException(e);
        }
    }

    @Override
    public <V> V decode(@Nonnull String sources, @Nonnull Class<V> target) throws SerializeException {
        try {
            if (!isJSON2(sources)) {
                return target.cast(sources);
            }
            return JSONObject.parseObject(sources, target);
        } catch (Exception e) {
            throw new SerializeException(e);
        }
    }

    public boolean isJSON2(String str) {
        boolean result = false;
        try {
            Object obj = JSON.parse(str);
            result = true;
        } catch (Exception ignored) {
        }
        return result;
    }
}
